<?php

namespace Admin\Controllers\Organizes;

use Admin\Controllers\BaseAdminController;
use Admin\Resources\OrganizeResources;
use Illuminate\Http\Request;
use Platform\Models\Organize\Organize;
use Platform\Repository\Organize\OrganizeRepository;
use Platform\System\Tools\ResultTool;

/**
 * 组织管理
 * Class UserController
 * @package App\Http\Controllers\Admin\System
 */
class OrganizeController extends BaseAdminController
{
    protected $org_repository;
    public function __construct(OrganizeRepository $org_repository)
    {
        parent::__construct();
        $this->org_repository = $org_repository;
    }

    /**
     * 组织列表
     *
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request){
        $organizes = $this->org_repository->screen($request);
        return myResult()->setData($organizes,OrganizeResources::class)->setPage($organizes)->send();
    }

    /**
     * 创建组织
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $data = $this->verify($request);

        $organize = $this->org_repository->create($data);
        $res = $this->org_repository->createDefaultLeader($organize);

        return myResult()->setData($res)->send();
    }

    /**
     * 编辑组织
     *
     * @param Request $request
     * @param Organize $organize
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Organize $organize)
    {
        $data = $this->verify($request,$organize);
        $organize->update($data);

        return myResult()->setCode(ResultTool::CODE_SUCCESS,'编辑成功')->send();
    }

    /**
     * 删除组织
     * @param Organize $organize
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(Organize $organize)
    {
        $organize->leader()->delete();
        $organize->delete();
        return myResult()->setCode(ResultTool::CODE_SUCCESS,'删除成功')->send();
    }

    /**
     * 数据验证
     * @param Request $request
     * @param Organize $organize
     * @return array
     */
    public function verify(Request $request,Organize $organize = null){

        $data = $request->only(['name','state']);

        $data['state'] = in_array($data['state'],[Organize::$STATE_NORMAL,Organize::$STATE_LOCK]) ? $data['state'] : Organize::$STATE_NORMAL;

        if (empty($data['name']))
            myResult()->stop(ResultTool::CODE_PARAM_LOST,'组织名称不可为空');

        if (getStrLength($data['name']) > 20)
            myResult()->stop(ResultTool::CODE_PARAM_WRONG,'组织名称过长');

        return $data;
    }
}
